package com.zhuangfei.hpuhelper.fragment;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.lzf.serviceplatform.R;

import com.hpu.bean.Course;
import com.hpu.bean.CourseListEntity;
import com.hpu.bean.Week;
import com.hpu.constants.HttpConstants;
import com.hpu.constants.ShareConstants;
import com.hpu.parser.CourseParser;
import com.hpu.parser.WeekParser;
import com.hpu.service.CourseService;
import com.hpu.service.LoginService;
import com.hpu.service.WeekService;
import com.hpu.tools.ShareTools;
import com.hpu.tools.TimeTools;
import com.zhuangfei.hpuhelper.tools.ActivityTools;
import com.zhuangfei.hpuhelper.tools.CourseTools;
import com.zhuangfei.hpuhelper.tools.DefaultHandler;
import com.zhuangfei.hpuhelper.tools.ReflectTools;
import com.zhuangfei.hpuhelper.view.CourseDetailActivity;
import com.zhuangfei.hpuhelper.view.CourseManagerActivity;
import com.zhuangfei.hpuhelper.view.MenuActivity;
import com.zhuangfei.hpuhelper.view.MyApplication;
import com.zhuangfei.hpuhelper.view.NoTimeClassActivity;
import com.zhuangfei.timetable.core.OnSubjectBindViewListener;
import com.zhuangfei.timetable.core.OnSubjectItemClickListener;
import com.zhuangfei.timetable.core.SubjectBean;
import com.zhuangfei.timetable.core.TimetableView;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.PopupMenu;
import android.widget.TextView;
import android.widget.Toast;

/**
 * 该碎片显示的是课表页面,用的TimetableView
 * 
 * @author Administrator 刘壮飞
 * 
 */
@SuppressLint({ "NewApi", "ValidFragment" })
public class CourseFragment extends Fragment implements OnSubjectItemClickListener,
		OnSubjectBindViewListener{

	private int cur_week = 1;

	private CourseService courseService;
	private LoginService loginService;
	private WeekService weekService;

	private TimetableView timetableView;
	private String term = "当前学期";

	TextView titleTextView;
	TextView termTextView;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		return inflater.inflate(R.layout.fragment_course, container, false);
	}

	@Override
	public void onViewCreated(View view, Bundle savedInstanceState) {
		super.onViewCreated(view, savedInstanceState);
		ButterKnife.bind(this,view);
		// 初始化
		initView(view);
		checkUpdate();
		loadData();
	}

	private void initView(View mView) {
		timetableView = (TimetableView) mView.findViewById(R.id.id_timetableView);
		titleTextView=mView.findViewById(R.id.id_title);
		termTextView=mView.findViewById(R.id.id_term);

		// 初始化帮助类
		courseService = new CourseService(handler, getActivity());
		loginService = new LoginService(getActivity(),handler);
		weekService = new WeekService(getActivity(), handler);
	}

	@Override
	public void onResume() {
		super.onResume();
		int check = (int) ShareTools.get(getActivity(), "course_update", 0);
		if (check == 1) {
			loadData();
			ShareTools.put(getActivity(), "course_update", 0);
		}
	}

	public void loadData() {
		CourseParser courseParser = new CourseParser();
		String courseString = (String) ShareTools.get(getActivity(), ShareConstants.STORE_COURSE, "");
		if (courseString == null || courseString.equals("")) {
			courseService.getCourse();
			return;
		}

		List<Course> courseBeans = courseParser.parse(courseString);
		if (courseBeans.size() > 0)
			term = courseBeans.get(0).getTerm();
		ShareTools.put(getActivity(), ShareConstants.STORE_TERM, term);

		List<Course> myCourseList = CourseTools.getCourseList(getActivity(), term);
		courseBeans.addAll(myCourseList);
		timetableView.setDataSource(transform(courseBeans))
				.setOnSubjectItemClickListener(this)
				.setOnSubjectBindViewListener(this)
				.bindTitleView(titleTextView)
				.setCurTerm(term)
				.setMax(true)
				.showTimetableView();
		timetableView.changeWeek(cur_week, true);
	}

	/**
	 * 检查是否需要去自动校准
	 */
	private void checkUpdate() {
		String start = ShareTools.get(getActivity(), ShareConstants.STORE_WEEK_STARTTIME, "").toString();
		if (start == null || start.equals("")) {
			weekService.getWeek();
		} else {
			cur_week = TimeTools.timeTransfrom(start);
			timetableView.changeWeek(cur_week, true);
		}
	}

	/**
	 * 获取到校准的时间后更新
	 * 
	 * @param string
	 */
	protected void handleWeek(String string) {
		WeekParser weekParser = new WeekParser();
		Week week = weekParser.parse(string);
		if (week != null) {
			ShareTools.put(getActivity(), ShareConstants.STORE_WEEK_STARTTIME, week.getStartTime());
			cur_week = TimeTools.timeTransfrom(week.getStartTime());
			System.out.println(cur_week);
			timetableView.changeWeek(cur_week, true);
		}

	}

	public List<SubjectBean> transform(List<Course> courses) {
		List<SubjectBean> subjectBeans = new ArrayList<>();
		Map<String, Integer> colorMap = new HashMap<>();
		int colorCount = 1;

		for (int i = 0; i < courses.size(); i++) {
			Course course = courses.get(i);
			int color;
			if (colorMap.containsKey(course.getName())) {
				color = colorMap.get(course.getName());
			} else {
				colorMap.put(course.getName(), colorCount);
				color = colorCount;
				colorCount++;
			}
			subjectBeans.add(new SubjectBean(course.getName(), course.getRoom(), course.getTeacher(), course.getWeekList(),
					course.getStart(), course.getStep(), course.getDay(), color,course.getTime()));
		}
		return subjectBeans;
	}

	DefaultHandler handler = new DefaultHandler(MyApplication.getInstance()) {
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			switch (msg.what) {
			// 获取课程成功
			case HttpConstants.QUERY_COURSE_SUCCESS:
				if (msg.obj.toString().indexOf("[") == -1) {
					Toast.makeText(getActivity(), "返回值出错:" + msg.obj.toString(), Toast.LENGTH_SHORT).show();
				} else {
					ShareTools.put(getActivity(), ShareConstants.STORE_COURSE, msg.obj.toString());
					loadData();
				}

				break;

			// 校准时间成功
			case HttpConstants.QUERY_WEEK_SUCCESS:
				handleWeek(msg.obj.toString());
				break;

			case HttpConstants.VPN_TOOLONG:
				if(handler.isIgnoreVpnExpired()){
					break;
				}
				loginService.login(ShareTools.get(getActivity(), ShareConstants.STORE_USER, "").toString(),
						ShareTools.get(getActivity(), ShareConstants.STORE_PASSWORD1, "").toString(),
						ShareTools.get(getActivity(), ShareConstants.STORE_PASSWORD2, "").toString());
				break;

			// 登录成功
			case HttpConstants.LOGIN_SUCCESS:
				ShareTools.put(getActivity(), ShareConstants.STORE_LOGINCOOKIE, (String) msg.obj);
				courseService.getCourse();
				break;
			}
		};
	};

	@Override
	public void onItemClick(View v, List<SubjectBean> subjectList) {
		List<Course> courses = new ArrayList<>();

		for (int i = 0; i < subjectList.size(); i++) {
			SubjectBean subjectBean = subjectList.get(i);

			courses.add(new Course(term, subjectBean.getName(), subjectBean.getRoom(), subjectBean.getTeacher(), subjectBean
					.getWeekList(), subjectBean.getStart(), subjectBean.getStep(), subjectBean.getDay(), subjectBean
					.getColorRandom(),subjectBean.getTime()));
		}

		CourseListEntity courseListEntity = new CourseListEntity(courses);
		ActivityTools.toActivityAnimByExtras(getActivity(), CourseDetailActivity.class, ReflectTools.EXTRAS_COURSE,
				courseListEntity);
	}

	public void onRightClick(View v) {
		PopupMenu popup = new PopupMenu(getActivity(), v);
		popup.getMenuInflater().inflate(R.menu.popmenu_course, popup.getMenu());

		popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
			public boolean onMenuItemClick(MenuItem item) {
				switch (item.getItemId()) {
				case R.id.top1:
					weekService.getWeek();
					courseService.getCourse();
					break;
				case R.id.top2:
					ActivityTools.toActivity(getActivity(), NoTimeClassActivity.class);
					
					break;
				case R.id.top3:
					ActivityTools.toActivity(getActivity(), CourseManagerActivity.class);
					break;
				default:
					break;
				}
				return true;
			}
		});

		popup.show();
	}

	@Override
	public void onBindTitleView(TextView titleTextView, int curWeek, String curTerm, List<SubjectBean> subjectBeans) {
		titleTextView.setText("第"+curWeek+"周");
		termTextView.setText(curTerm);
	}

	@OnClick(R.id.id_main_menu)
	public void toMenuActivity(){
		ActivityTools.toActivity(getActivity(), MenuActivity.class);
	}
}
